package me.firstapp.repository.system.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.system.EmailConfig;
import me.firstapp.repository.base.impl.EntityRepositoryImpl;
import me.firstapp.repository.system.EmailConfigRepository;

@Repository
public class EmailConfigRepositoryImpl extends EntityRepositoryImpl<EmailConfig> implements EmailConfigRepository {

	@Override
	protected Class<EmailConfig> getPersistentClass() {
		return EmailConfig.class;
	}

	@Override
	public EmailConfig findByApiClientIdAndStatus(Long apiClientId, Integer status) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder(" FROM EmailConfig bean WHERE 1=1 ");

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);

		sql.append(" AND bean.status =:status ");
		parameters.put("status", status);

		List<EmailConfig> result = super.query(EmailConfig.class, sql.toString(), parameters);
		return result.isEmpty() ? null : result.get(0);
	}

	@Override
	public EmailConfig findById(Long id, Long apiClientId) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder(" FROM EmailConfig bean WHERE 1=1 ");

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);

		sql.append(" AND bean.id =:id ");
		parameters.put("id", id);

		List<EmailConfig> result = super.query(EmailConfig.class, sql.toString(), parameters);
		return result.isEmpty() ? null : result.get(0);
	}

	@Override
	public Page<EmailConfig> findEmailConfigPage(Integer pageNo, Integer pageSize, Map<String, Object> searchParams,
			String sortParam, String sortType, Long apiClientId) {
		StringBuilder sql = new StringBuilder(" FROM EmailConfig bean where 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		if (searchParams != null) {
			Set<String> keys = searchParams.keySet();
			for (String key : keys) {
				Object value = searchParams.get(key);
				if (value != null) {
					sql.append(" AND bean." + key + " LIKE :value ");
					parameters.put("value", "%" + value + "%");
				}
			}
		}

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);

		if (StrUtils.isNotNULL(sortParam) && StrUtils.isNotNULL(sortType)) {
			sql.append(" ORDER BY " + sortParam + " " + sortType);
		}

		return super.queryForPage(EmailConfig.class, sql.toString(), parameters, pageNo, pageSize);
	}

}
